package com.aatattoo.light_food_service.service;

import com.aatattoo.light_food_service.entity.DynamicImg;
import com.aatattoo.light_food_service.mapper.DynamicImgMapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.List;

/**
 * @Author aatattoo
 * @Date 2021/12/9 10:10 下午
 * @msg:
 */
@Service
@Component
public class DynamicImgService {
    @Autowired
    private DynamicImgMapper dynamicImgMapper;

    private String imgPath="C:/uploadfiles/dynamicImg/";
//    private String imgPath="/Users/aatattoo/Desktop/file/";

    /**
     * 批量上传增加图片，未新添加图片增加图片排序与图片地址
     * @param dynamicImg #{address}图片地址,#{order}图片排序
     * @return 新增图片的id值
     */
    public int addDynamicImg(DynamicImg dynamicImg){
        dynamicImgMapper.addDynamicImg(dynamicImg);
        return dynamicImg.getId();
    }

    public int updataDynamicImg(DynamicImg dynamicImg){
        return dynamicImgMapper.updataDynamicImg(dynamicImg);
    }


    public int updataDynamicImgOrder(DynamicImg dynamicImg){
        return dynamicImgMapper.updataDynamicImgOrder(dynamicImg);
    }

    public List<DynamicImg> findByDynamicId(int dynamicId){
        return dynamicImgMapper.findByDynamicId(dynamicId);
    }
    public int deleteDynamicImg(int dynamicId){
        return dynamicImgMapper.deleteDynamicImg(dynamicId);
    }

    public int deleteById(int id){
        return dynamicImgMapper.deleteById(id);
    }

    public List<Object> getID(int dynamicId){
        return dynamicImgMapper.getID(dynamicId);
    }

    public int updataDynamicOrder(DynamicImg dynamicImg){
        return dynamicImgMapper.updataDynamicOrder(dynamicImg);
    }

    public DynamicImg findById(int id){
        return dynamicImgMapper.findById(id);
    }

    public List<DynamicImg> findAllByDynamicID(int dynamicId){
        return dynamicImgMapper.findAllByDynamicID(dynamicId);
    }

    public String findFirstByDynamicId(int dynamicId){
        return dynamicImgMapper.findFirstByDynamicId(dynamicId);
    }

    /**
     * 删除所有文件
     * @param id  表单id
     */
    public void deleteImgAllFile(int id){
        dynamicImgMapper.findByDynamicId(id).forEach(img->{
            String imgName = img.getAddress().split("/")[img.getAddress().split("/").length - 1];
            File dir=new File(imgPath+imgName);
            if (dir.exists()){
                dir.delete();
            }
        });
    }

    /**
     * 删除单个文件
     * @param id 图片表单主键id
     */
    public void deleteImgFile(int id){
        DynamicImg img = findById(id);
        String imgName = img.getAddress().split("/")[img.getAddress().split("/").length - 1];
        File dir=new File(imgPath+imgName);
        if (dir.exists()){
            dir.delete();
        }
    }




}
